// src/utils/request.js
import axios from 'axios';
import {ElMessage} from 'element-plus';

const service = axios.create({
    baseURL: 'http://localhost:8081',
    timeout: 5000,
    withCredentials: true // 允许携带凭证
});

// 请求拦截器
service.interceptors.request.use(
    config => {
        // 从 localStorage 获取 token 并添加到请求头
        const token = localStorage.getItem('satoken');
        if (token) {
            config.headers['satoken'] = token;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        // 处理认证失败的情况
        if (error.response && error.response.status === 401) {
            ElMessage.error('登录已过期，请重新登录');
            // 清除本地存储的 token 和用户信息
            localStorage.removeItem('satoken');
            localStorage.removeItem('userInfo');
            // 跳转到登录页
            window.location.href = '/Login';
        }
        return Promise.reject(error);
    }
);

export default service;
